<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2022/5/9
 * Time: 下午4:48
 */

namespace app\api\controller\v32;

use app\api\controller\v13\Auth2;
use app\api\controller\v2\Auth;
use app\common\cachemodel\lucky\AppLuckyDraw;
use app\common\cachemodel\lucky\AppLuckyExchange;
use app\common\cachemodel\lucky\AppLuckyTaskRecord;
use app\common\cachemodel\lucky\AppUserAdornInfo;
use app\common\cachemodel\lucky\AppUserLuckyChangeRecord;
use app\common\cachemodel\lucky\AppUserLuckyInfo;
use app\common\cachemodel\lucky\AppUserOldLuckyRecycle;
use app\common\cachemodel\MallUserAddress;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use app\common\model\Recode;
use think\Db;
use think\Env;

/**
 * 幸运星改版
 * Class LuckyPlanet
 * @package app\api\controller\v32
 */
class LuckyPlanet extends Auth
{
    protected $starImg = 'https://oss.goddessxzns.com/test/lucky_star/star.png';

    /**
     * 幸运星首页
     */
    public function index()
    {
        $date = date('Ymd');
        $luckyTaskRecordModel = new AppLuckyTaskRecord();

        $luckyInfo = (new AppUserLuckyInfo())->IndexGetUserLuckyInfo($this->user['id']);

        $taskInfo = $luckyTaskRecordModel->getTaskList($this->user['id'], $this->user['rid'] ?? 0);
        // 获取幸运星 领取信息
        $userLuckyChangeRecordModel = new AppUserLuckyChangeRecord();
        // 获取明日即将过期
        $expireSoonNum = $luckyInfo['lucky_num'] > 0 ? $userLuckyChangeRecordModel->getExpireLuckyNumByTomorrow($this->user['id']) : 0;

        $signInInfo = $userLuckyChangeRecordModel->getUserSignInfoByToday($this->user['id'], $date);
        if ($signInInfo['num'] < $luckyTaskRecordModel->MaxSignInNum)
        {
            $status = 1;
            $t = $signInInfo['time'] + $luckyTaskRecordModel->SignInInterval - $this->request->time();
            $lastTime = $t > 0 ? $t : 0;
        } else
        {
            $status = 0;
            $lastTime = 0;
        }

        $data = [
            // 页面顶部数据
            'top_info' => [
                'have_num' => $luckyInfo['lucky_num'], // 当前拥有幸运星数量
                'expire_soon_num' => $expireSoonNum, // 明日即将摧毁的数量
                'introduce_title' => '什么是幸运星？幸运星又能做什么呢？', // 介绍的标题
                'status' => $status, // 0=>不能签到（明天再来）,1=>可以签到
                'last_time' => $lastTime, // 倒计时秒数，status=1且last_time=0的时候能签到，否则进行倒计时展示
                'target' => 'link', // 介绍的H5跳转地址
                'link' => Env::get('host.domain') . '/web/lucky_star/whatsnew.html', // 介绍的H5跳转地址
                'img' => $this->starImg, // 当前拥有23颗幸运星前面的那个小图片的地址
            ],
            // 任务数据
            'task_info' => [
                // 每日任务
                'everyday' => [
                    'name' => '每日任务',
                    'tips' => '每日凌晨0点刷新任务',
                    'list' => $taskInfo['everyday'],
                ],
                // 升级任务
                'upgrade' => [
                    'name' => '升级任务',
                    'tips' => '',
                    'list' => $taskInfo['upgrade'],
                ],
                // 其他任务
                'other' => [
                    'name' => '其他任务',
                    'tips' => '',
                    'list' => $taskInfo['other'],
                ],
            ],
            'first_info' => $luckyInfo['first_info'] ? ['compensation_text' => $luckyInfo['first_info']] : null
        ];

        return show(200, '请求成功', $data);
    }

    /**
     * 获取 幸运星小红点
     */
    public function getLuckyIsNew()
    {
        $status = (new AppLuckyTaskRecord())->getIndexIsNew($this->user['id']);

        return show(config('code.success'), '请求成功', [
            'status' => $status
        ]);
    }

    /**
     * 销毁幸运星 知道了
     * @return \think\response\Json
     * @throws \Exception
     */
    public function recycleKnow()
    {
        $userLuckyInfoModel = new AppUserLuckyInfo();
        $userLuckyInfo = $userLuckyInfoModel->getInfoById($this->user['id']);
        if ($userLuckyInfo)
        {
            return show(config('code.success'), '请求成功');
        }

        (new AppUserOldLuckyRecycle())->confirmRecycle($this->user['id']);

        return show(config('code.success'), '请求成功');
    }

    /**
     * 签到
     */
    public function SignIn()
    {
        $date = date('Ymd');
        $userLuckyChangeRecordModel = new AppUserLuckyChangeRecord();
        $userLuckyInfoModel = new AppUserLuckyInfo();
        $luckyTaskRecordModel = new AppLuckyTaskRecord();

        $luckyTaskConfig = config('lucky_task.task_list');

        $signInInfo = $userLuckyChangeRecordModel->getUserSignInfoByToday($this->user['id'], $date);

        if ($signInInfo['num'] >= $luckyTaskRecordModel->MaxSignInNum)
        {
            return show(config('code.error'), '今日幸运星签到次数已满～');
        }

        if ($this->request->time() - $signInInfo['time'] < $luckyTaskRecordModel->SignInInterval)
        {
            return show(config('code.error'), '签到时间未到，请稍后再来领取～');
        }

        $res = $userLuckyInfoModel->userLuckyNumSend($this->user['id'], 1, '签到');

        if ($res)
        {
            // 记录本次签到信息
            $userLuckyChangeRecordModel->updateSignInData($this->user['id'], $date, [
                'num' => $signInInfo['num'] + 1,
                'time' => $this->request->time()
            ]);

            // 神策打点 208 幸运星-签到 LuckyStarSignIn
            SensorsData::track($this->user['id'], true, 'LuckyStarSignIn', [
                'today_sign_times' => $signInInfo['num'] + 1,   // 单日签到次数
            ]);

            return show(config('code.success'), '签到领取成功', [
                'title' => '领取成功',
                'img' => 'https://oss.goddessxzns.com/test/lucky_star/lotto-4-tip.png',
                'name' => '幸运星 +' . $luckyTaskConfig[1]['lucky_num'],
                'des' => '可用于抽奖或兑换外观装扮',
            ]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 每日任务完成
     * @return \think\response\Json
     * @throws \Exception
     */
    public function taskSuccess()
    {
        $taskId = input('task_id/d', 0);
        $luckyTaskConfig = config('lucky_task');

        if (!in_array($taskId, $luckyTaskConfig['everyday'], true))
        {
            return show(config('code.success'), '服务异常，请稍后再试～');
        }

        if ($taskId === 4 && Util::CheckAppVersion('2.9.7') === '大')
        {   // 2.9.8 版本 每日运势日记 任务删除
            return show(config('code.success'), '服务异常，请稍后再试～');
        }
        if (Util::commentCheck($this->user['id'], ['action' => 'taskSuccess', 'lucky_task_id' => $taskId]))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }

        $luckyTaskRecordModel = new AppLuckyTaskRecord();

        $date = date('Ymd');
        // 获取每日任务完成 信息
        $taskSuccessInfo = $luckyTaskRecordModel->getEverydayTaskSuccessData($this->user['id'], $date);

        if (isset($taskSuccessInfo[$taskId]))
        {   // 任务已完成
            return show(config('code.success'), '任务完成');
        }

        $res = $luckyTaskRecordModel->setEverydayTaskSuccess($this->user['id'], $date, $taskId);
        if ($res)
        {
            return show(config('code.success'), '任务完成', [
                'lucky_toast' => [
                    "title" => $luckyTaskConfig['task_list'][$taskId]['toast_name'],
                    "img" => $luckyTaskConfig['task_list'][$taskId]['img'],
                    "des" => "x{$luckyTaskConfig['task_list'][$taskId]['lucky_num']}可领取"
                ]
            ]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 领取 幸运星 完成任务的幸运星
     */
    public function getTaskStar()
    {
        $taskId = input('task_id/d', 0);

        if (Util::commentCheck($this->user['id'], ['lucky_task_id' => $taskId]))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }

        $luckyTaskConfig = config('lucky_task');
        if (!isset($luckyTaskConfig['task_list'][$taskId]) || $taskId === 1)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $date = date('Ymd');
        $luckyTaskRecordModel = new AppLuckyTaskRecord();
        $userLuckyInfoModel = new AppUserLuckyInfo();
        switch (true)
        {
            case in_array($taskId, $luckyTaskConfig['everyday'], true):
                // 领取每日任务 幸运星 奖励
                $taskSuccessInfo = $luckyTaskRecordModel->getEverydayTaskSuccessData($this->user['id'], $date);

                if (!isset($taskSuccessInfo[$taskId]))
                {
                    return show(config('code.error'), '领取失败，还未完成任务～');
                }

                if ($taskSuccessInfo[$taskId] == 2)
                {
                    return show(config('code.error'), '领取失败，已经领取过奖励了～');
                }
                // 幸运星发放
                $res = $userLuckyInfoModel->userLuckyNumSend($this->user['id'], $taskId, '每日任务');
                if ($res)
                {
                    $luckyTaskRecordModel->everydayTaskSuccessSetGive($this->user['id'], $date, $taskId);
                } else
                {
                    return show(config('code.error'), '服务异常，请稍后再试～');
                }
                break;
            case in_array($taskId, $luckyTaskConfig['upgrade'], true):
                // 领取升级任务 幸运星 奖励
                $taskSuccessInfo = $luckyTaskRecordModel->getUpgradeTaskSuccessData($this->user['id'], $date);
                if ($taskSuccessInfo[$taskId]['type'] == 2)
                {
                    return show(config('code.error'), '领取失败，已经领取过奖励了～');
                }

                if ($taskSuccessInfo[$taskId]['day'] < $luckyTaskConfig['task_list'][$taskId]['day'])
                {
                    return show(config('code.error'), '领取失败，还未完成任务～');
                }
                // 幸运星发放
                $res = $userLuckyInfoModel->userLuckyNumSend($this->user['id'], $taskId, '升级任务');
                if ($res)
                {
                    $luckyTaskRecordModel->upgradeTaskSuccessSetGive($this->user['id'], $date, $taskId);
                } else
                {
                    return show(config('code.error'), '服务异常，请稍后再试～');
                }
                break;
            case in_array($taskId, $luckyTaskConfig['other'], true):
                // 领取其他任务 幸运星 奖励
                $taskSuccessInfo = $luckyTaskRecordModel->getOtherTaskSuccessData($this->user['id']);
                if (!$taskSuccessInfo[$taskId])
                {
                    return show(config('code.error'), '领取失败，还未完成任务～');
                }

                if ((int)$taskSuccessInfo[$taskId] === 2)
                {
                    return show(config('code.error'), '领取失败，已经没有东西可领了～');
                }
                // 幸运星发放
                $res = $userLuckyInfoModel->userLuckyNumSend($this->user['id'], $taskId, '其他任务');
                if ($res)
                {
                    $luckyTaskRecordModel->otherTaskSuccessSetGive($this->user['id'], $taskId);
                } else
                {
                    return show(config('code.error'), '服务异常，请稍后再试～');
                }
                break;
            default:
        }

        return show(config('code.success'), '领取成功', [
            'title' => '领取成功',
            'img' => 'https://oss.goddessxzns.com/test/lucky_star/lotto-4-tip.png',
            'name' => '幸运星 +' . $luckyTaskConfig['task_list'][$taskId]['lucky_num'],
            'des' => '可用于抽奖或兑换外观装扮',
        ]);
    }

    /**
     * 兑换页面
     */
    public function exchangeDataLists()
    {
        $luckyInfo = (new AppUserLuckyInfo())->IndexGetUserLuckyInfo($this->user['id']);
        // 获取幸运星 领取信息
        $userLuckyChangeRecordModel = new AppUserLuckyChangeRecord();
        // 获取明日即将过期
        $expireSoonNum = $luckyInfo['lucky_num'] > 0 ? $userLuckyChangeRecordModel->getExpireLuckyNumByTomorrow($this->user['id']) : 0;

        $resData = (new AppLuckyExchange())->getExchangeLists($this->user['id']);
        //  修改为正式数据
        $data = [
            // 页面顶部数据
            'top_info' => [
                'have_num' => $luckyInfo['lucky_num'] ?? 0, // 当前拥有幸运星数量
                'expire_soon_num' => $expireSoonNum, // 明日即将摧毁的数量
                'notice' => '幸运星有效期30日，到期将自动销毁。',
                'img' => $this->starImg, // 当前拥有23颗幸运星前面的那个小图片的地址
            ],
            // 兑换列表数据
            'list' => [
                [
                    'title' => '徽章',
                    'list' => $resData[2],
                    'tab_index' => 2
                ],
                [
                    'title' => '头像框',
                    'list' => $resData[1],
                    'tab_index' => 0
                ],
                [
                    'title' => '动态标签',
                    'list' => $resData[3],
                    'tab_index' => 1
                ],
            ],
        ];

        return show(200, '请求成功', $data);
    }

    /**
     * 历史记录
     */
    public function history()
    {
        // 0=>全部,1=>领取,2=>使用,3=>销毁
        $type = input('type/d', 0);
        $luckyInfo = (new AppUserLuckyInfo())->IndexGetUserLuckyInfo($this->user['id']);
        // 获取幸运星 领取信息
        $userLuckyChangeRecordModel = new AppUserLuckyChangeRecord();
        // 获取明日即将过期
        $expireSoonNum = $luckyInfo['lucky_num'] > 0 ? $userLuckyChangeRecordModel->getExpireLuckyNumByTomorrow($this->user['id']) : 0;

        $resData = $userLuckyChangeRecordModel->LuckyNumChangeRecord($this->user['id'], $type);

        //  修改为正式数据
        $data = [
            // 页面顶部数据
            'top_info' => [
                'have_num' => $luckyInfo['lucky_num'] ?? 0, // 当前拥有幸运星数量
                'expire_soon_num' => $expireSoonNum, // 明日即将摧毁的数量
                'notice' => '幸运星有效期30日，到期将自动销毁。',
                'img' => $this->starImg, // 当前拥有23颗幸运星前面的那个小图片的地址
            ],
            // 列表数据
            'list' => $resData,
        ];

        return show(200, '请求成功', $data);
    }

    /**
     * 个性装扮详情
     */
    public function profile()
    {
        $userAdornLists = (new AppUserAdornInfo())->getUserHasAdornLists($this->user['id']);
        if ($this->user['rid'])
        {
            $recode = (new Recode())->getRecode(['id' => $this->user['rid']]);
            if ($recode)
            {
                $utilModel = new Util();
                $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);
            }
        }
        //  注意默认头像框和默认标签的ID必须为0
        $data = [
            // 用户信息
            'userinfo' => [
                'nickname' => $this->user['nickname'], // 昵称
                'avatar' => $this->user['avatar'], // 头像
                'user_des' => $userDes ?? '小行星神秘人', // 日月升信息
                // 徽章，最多展示两个徽章 [颜值巅峰、点赞好运]
                'badge' => $userAdornLists['badge'],
            ],
            // 头像框列表
            'adorn_list' => $userAdornLists['adorn_list'],
            // 动态标签列表
            'tag_list' => $userAdornLists['tag_list'],
            // 徽章列表
            'badge_list' => $userAdornLists['badge_list'],
            'badge_max_num' => 2, // 可选择的徽章最大数量
        ];

        return show(200, '请求成功', $data);
    }

    /**
     * 幸运星抽奖
     */
    public function draw()
    {
        if (Util::commentCheck($this->user['id'], ['lucky_draw' => 1]))
        {
            return show(config('code.error'), '别心急，等一等');
        }
        $userLuckyInfoModel = new AppUserLuckyInfo();
        $luckyInfo = $userLuckyInfoModel->getInfoById($this->user['id']);

        if ($luckyInfo['lucky_num'] < 10)
        {
            return show(config('code.error'), '幸运星不够，抽奖失败');
        }
        $LuckyDrawModel = new AppLuckyDraw();
        $draw = $LuckyDrawModel->getDrawResult($this->user['id']);
        // 抽奖扣除幸运星 并记录 幸运星使用记录
        $res = (new AppUserLuckyChangeRecord())->luckyDrawSave($luckyInfo, $draw);
        if ($res)
        {
            if ($draw['is_show_tips'] === 1)
            {
                $nickname = $this->user['nickname'] ?: '匿名用户';

                $LuckyDrawModel->setDrawRecordCacheAdd("{$nickname}获得了\"{$draw['name']}\"");
            }

            $luckynum = $userLuckyInfoModel->getInfoById($this->user['id'], ['lucky_num']);

            $drawType = [
                0 => '下次再来',
                1 => '卡券',
                2 => '准币',
                3 => '实物',
                4 => '装扮',
                5 => '幸运星',
            ];
            // 神策打点 201 幸运星参与抽奖 LuckyStarDraw
            SensorsData::track($luckyInfo['uid'], true, 'LuckyStarDraw', [
                'star_left' => $luckynum['lucky_num'], // 兑换后剩余的余额
                'draw_type' => $drawType[$draw['type']],      //奖品类型  实物、卡券、准币、幸运星、装扮
                'draw_result' => $draw['name'],    // 显示具体名称数量：幸运星*16、准了口罩、1888准币、幸运星*10、限定徽章、一生报告券、2888准币、下次好运、幸运星*12、年运2折
            ]);

            return show(config('code.success'), '抽奖成功', [
                'id' => $draw['index'],
                'name' => $draw['name'],
                'type' => $draw['type'],
                'pic' => $draw['pic'],
                'lucky_num' => $luckynum['lucky_num']
            ]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 装扮 兑换
     */
    public function adornExchange()
    {
        $id = input('id/d', 0);
        if (!$id)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $userLuckyInfoModel = new AppUserLuckyInfo();
        $luckyInfo = $userLuckyInfoModel->getInfoById($this->user['id']);

        $adornInfo = (new AppLuckyExchange())->getInfoById($id);

        if ($adornInfo['lucky_num'] > $luckyInfo['lucky_num'])
        {
            return show(config('code.error'), '幸运星数量不足，兑换失败～');
        }

        if ((new AppUserAdornInfo())->UserIsHasAdorns($this->user['id'], $id))
        {
            return show(config('code.error'), '装扮已经拥有，兑换失败～');
        }

        $res = (new AppUserLuckyChangeRecord())->luckyExchangeAdorn($luckyInfo, $adornInfo);
        if ($res)
        {
            return show(config('code.success'), '兑换成功', [
                'title' => '兑换成功',
                'img' => $adornInfo['photo']['img']['url'],
                'name' => $adornInfo['name'],
                'des' => '有效期：30天',
            ]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 保存装扮
     */
    public function saveAdorns()
    {
        $adornId = input('adorn/d', 9999);
        $tagId = input('tag/d', 9999);
        $badgeIds = input('badge/a', []);
        $badgeIds = array_filter($badgeIds);
        if ($adornId === 9999 || $tagId === 9999)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $userLuckyChangeRecordModel = new AppUserLuckyChangeRecord();

        $UserAdornInfoModel = new AppUserAdornInfo();
        $exchangeModel = new AppLuckyExchange();
        $userAdornLists = $UserAdornInfoModel->getUserHasAdornLists($this->user['id']);
        $userAdornIds = array_column($userAdornLists['adorn_list'], 'id');
        if (!in_array($adornId, $userAdornIds, true))
        {
            return show(config('code.error'), '服务异常，头像框不存在～');
        }
        $luckyAdornConfig = config('lucky_adorn');

        $adornDataList = [];// 打点使用
        $data = [];
        if ($adornId === 0 || $adornId === $luckyAdornConfig['vip_adorn'])
        {   // 默认无头像框  或者 vip 头像框
            $data['adorn_info'] = ['id' => $adornId, 'exId' => 0, 'expire_time' => 0];
            if ($adornId === 0)
            {
                $adornDataList[] = '无头像框';
            } else
            {
                $adornDataList[] = '会员头像框';
            }
        } else
        {
            $info = $userLuckyChangeRecordModel->getInfoById($adornId, ['id', 'exchange_id', 'expire_time']);
            $data['adorn_info'] = ['id' => $adornId, 'exId' => $info['exchange_id'], 'expire_time' => $info['expire_time']];
            $info1 = $exchangeModel->getInfoById($info['exchange_id'], ['name']);
            $adornDataList[] = $info1['name'];
        }
        $userTagIds = array_column($userAdornLists['tag_list'], 'id');
        if (!in_array($tagId, $userTagIds, true))
        {
            return show(config('code.error'), '服务异常，标签不存在～');
        }
        if ($tagId === 0)
        {   // 默认标签
            $data['tag_info'] = ['id' => $tagId, 'exId' => 0, 'expire_time' => 0];
            $adornDataList[] = '默认标签';
        } else
        {
            $info = $userLuckyChangeRecordModel->getInfoById($tagId, ['id', 'exchange_id', 'expire_time']);
            $data['tag_info'] = ['id' => $tagId, 'exId' => $info['exchange_id'], 'expire_time' => $info['expire_time']];
            $info1 = $exchangeModel->getInfoById($info['exchange_id'], ['name']);
            $adornDataList[] = $info1['name'];
        }
        $userBadgeIds = array_column($userAdornLists['badge_list'], 'id');
        foreach ($badgeIds as $id)
        {
            $id = (int)$id;
            if (!in_array($id, $userBadgeIds, true))
            {
                return show(config('code.error'), '服务异常，徽章不存在～');
            }
            if ($id === $luckyAdornConfig['vip_badge'])
            {
                $data['badge_info'][] = ['id' => $id, 'exId' => 0, 'expire_time' => 0];
                $adornDataList[] = '会员徽章';
            } else
            {
                $info = $userLuckyChangeRecordModel->getInfoById($id, ['id', 'exchange_id', 'expire_time']);
                $data['badge_info'][] = ['id' => $id, 'exId' => $info['exchange_id'], 'expire_time' => $info['expire_time']];
                $info1 = $exchangeModel->getInfoById($info['exchange_id'], ['name']);
                $adornDataList[] = $info1['name'];
            }
        }

        $adornConfig = $UserAdornInfoModel->getUserAdornConfig($this->user['id']);

        $ConfigId = $adornConfig ? $adornConfig['id'] : 0;
        $data['adorn_info'] = json_encode($data['adorn_info'], JSON_UNESCAPED_UNICODE);
        $data['tag_info'] = json_encode($data['tag_info'], JSON_UNESCAPED_UNICODE);
        $data['badge_info'] = isset($data['badge_info']) ? json_encode($data['badge_info'], JSON_UNESCAPED_UNICODE) : '[]';
        $res = $UserAdornInfoModel->SaveUserAdornConfig($ConfigId, $this->user['id'], $data);
        if ($res)
        {
            // 神策打点 203 装扮成功 UserAdornSave
            SensorsData::track($this->user['id'], true, 'UserAdornSave', [
                'adorn_item' => $adornDataList,   // 装扮项目
            ]);

            return show(config('code.success'), '装扮成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 更换|选择收货地址
     */
    public function setAddress()
    {
        $addressId = input('address_id/d', 0);
        $historyId = input('history_id/d', 0);

        if ($addressId === 0 || $historyId === 0)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $addressInfo = (new MallUserAddress())->getInfoById($addressId);
        if (!$addressInfo || (int)$addressInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，地址信息不存在～');
        }

        $userLuckyChangeRecordModel = new AppUserLuckyChangeRecord();

        $historyInfo = $userLuckyChangeRecordModel->getInfoById($historyId);

        if (!$historyInfo || $historyInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '数据不存在，请稍确认后重试～');
        }

        if ($historyInfo['status'] === 2)
        {
            return show(config('code.error'), '已发货，更换失败～');
        } elseif ($historyInfo['status'] === 1)
        {   // 更新
            $addressData = [
                'mall' => [
                    'address_id' => $addressId,
                    'address' => $addressInfo['country'] . '，' . $addressInfo['province'] . '，' . $addressInfo['city'] . '，' . $addressInfo['address_desc'],
                    'is_faraway' => (int)$addressInfo['is_faraway'],
                    'phone' => $addressInfo['phone'],
                    'name' => $addressInfo['name'],
                    'kd_id' => '',
                    'kd_name' => '',
                    'remark' => '',
                    'kd_send_time' => ''
                ]
            ];

            $res = $userLuckyChangeRecordModel->UpdateData($historyId, [
                'status' => 1,
                'extend' => json_encode($addressData, JSON_UNESCAPED_UNICODE)
            ]);
        } else
        {   // 设置
            $drawInfo = (new AppLuckyDraw())->getInfoById($historyInfo['draw_id'], ['type']);

            if ($drawInfo['type'] !== 3)
            {
                return show(config('code.error'), '数据异常，请稍后再试～');
            }

            $addressData = [
                'mall' => [
                    'address_id' => $addressId,
                    'address' => $addressInfo['country'] . '，' . $addressInfo['province'] . '，' . $addressInfo['city'] . '，' . $addressInfo['address_desc'],
                    'is_faraway' => (int)$addressInfo['is_faraway'],
                    'phone' => $addressInfo['phone'],
                    'name' => $addressInfo['name'],
                    'kd_id' => '',
                    'kd_name' => '',
                    'remark' => '',
                    'kd_send_time' => ''
                ]
            ];

            $res = $userLuckyChangeRecordModel->UpdateData($historyId, [
                'status' => 1,
                'extend' => json_encode($addressData, JSON_UNESCAPED_UNICODE)
            ]);
        }

        if ($res)
        {
            return show(config('code.success'), '操作成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }
}
